const mysql = require('mysql2');
const { Web3 } = require('web3');
const contractJson = require('E:/Vue3/vite-project/bin/sol/DonationPlatform.json');
const bin = require("E:/Vue3/vite-project/bin/sol/DonationPlatform.json").bin;


const web3 = new Web3('http://127.0.0.1:7545');

// ✅ 请将此处替换为你部署后的实际合约地址
const contractAddress = bin;
const contract = new web3.eth.Contract(contractJson.abi, contractAddress);

// 连接数据库
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'donation_platform'
});

async function uploadProjects() {
  const accounts = await web3.eth.getAccounts();
  const from = accounts[0]; // 使用第一个账户

  db.query('SELECT * FROM hot_projects', async (err, results) => {
    if (err) {
      console.error('数据库查询失败:', err);
      return;
    }

    for (const project of results) {
      try {
        console.log('上传项目:', project.name);

        await contract.methods.createProject(
          project.name,
          project.shortDescription,
          project.description,
          project.image,
          parseInt(project.goal),
          parseInt(project.raised),
          String(project.progress) + "%",     // 转为字符串，如 "60"
          parseInt(project.donors),
          project.tag,
          project.status,
          project.walletAddress
        ).send({ from, gas: 5000000 });

        console.log(`✅ 上链成功: ${project.name}`);
      } catch (e) {
        console.error(`❌ 上链失败: ${project.name}`, e.message);
      }
    }

    db.end();
  });
}

uploadProjects();
